<template>
  <div class="paper-container">    
    <el-container>

    <el-header style="height:inherit;">      
      <el-form :model="PaperForm" :rules="rules" ref="PaperForm" :inline="true" class="demo-form-inline margindis">
        <el-form-item label="试卷名称" required prop="title">
          <el-input v-model="PaperForm.title"></el-input>
        </el-form-item>
        <el-form-item label="选择分类" required prop="typeList">
          <el-cascader
            :options="options"
            v-model="PaperForm.typeList"
            change-on-select>
          </el-cascader>
        </el-form-item>
        <el-form-item label="答卷时长" required prop="examTime">
          <el-input v-model="PaperForm.examTime" class="time-input"></el-input>
          &nbsp;分钟
        </el-form-item>
        <el-form-item label="通过分数" required prop="passLine">
          <el-input v-model="PaperForm.passLine" class="time-input"></el-input>
          &nbsp;分
        </el-form-item>
        <div class="write-exam">
          <el-form-item label="试卷说明" required prop="remarks">
          <el-input type="textarea" v-model="PaperForm.remarks" class="textarea" resize="none"></el-input>
          </el-form-item>
        </div>      
      </el-form>
    </el-header>

      <el-container class="container">
        <el-aside width="40%">
              <div style="margin-top: 20px" class="btn-layout">
                <el-button class="filter-item" type="primary" v-waves icon="search" @click="showView('ViewAdd')">手动添加</el-button>
                <el-button class="filter-item" type="primary" v-waves icon="search" @click="showView('ViewImport')">批量导入</el-button>
                <el-button class="filter-item" type="primary" v-waves icon="search" @click="showView('ViewSelect')">从我的题库选择</el-button>
              </div>
          <div class="btn-bottom">
          <div class="scroll-bar">
              <el-table class="borderdel" :data="tableData" style="width: 100%">
                
                <el-table-column prop="id" type="index" label="序号" width="100"></el-table-column>
                <el-table-column prop="question" label="题目" width="100"></el-table-column>
                <el-table-column prop="classify" label="题型" width="100"></el-table-column>
                <!-- <el-table-column prop="examType.typeName" label="分类" width="100"></el-table-column> -->
            
                <el-table-column align="right" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <el-input  v-model="goods[scope.$index]" placeholder="分值" @change="sumScore"></el-input>                    
                    <el-button @click.native.prevent="deleteRow(scope.$index, tableData)"><i class="el-icon-delete"></i></el-button>
                  </template>
                </el-table-column>                
              </el-table>

            </div>
          </div>
              <el-footer style="height: inherit">
                <div style="margin-top: 20px" class="footer">
                  <p>
                    总题数:<span v-html="this.questionCount">x</span>道  
                  </p>
                  <p>
                    总分数:<span v-html="this.questionScore">x</span>分  
                  </p>
              <div class="preview">
                <el-badge class="item">
                     <div class="review-container">
                    <el-dialog
                    :visible.sync="dialogVisible"
                    width="40%"
                    :before-close="handleClose"
                    v-loading="dialogLoading"
                    >
                    <div class="test-type">
                            <div class="qr-code">
                                <div>二维码图片</div>
                                <div>手机扫码预览</div>
                            </div>
                            <h4>java初级</h4>
                        </div>
                    <div class="scroll-bar">
                    <div class="review-header">
                        
                        <div class="test-document">
                          <span>答卷时长:<span v-html="this.PaperForm.examTime"></span> 分钟</span>
                          <span>共 <span v-html="this.questionCount"></span> 题 满分 <span v-html="this.questionScore"></span> 分</span>                          
                        </div>
                        <div class="documet-note clearfix"><div>试卷说明：</div> 
                            <div v-html="this.PaperForm.remarks">                                            
                            </div>
                        </div>
                    </div>
                      <div class="review-body">
                        <dl                          
                          v-for="(item, index) in questionOptionList"                          
                          :key="item.key"
                        >
                          <dt>
                            <span v-html="index+1 + '、' + item.question + '（）'"></span>
                            <span v-html="item.questionNo"></span>
                          </dt>

                          <dd
                          v-for="(item2, index2) in item.domains"                          
                          :key="item2.key"
                          v-html="numberConvertLetterFun(index2) + '．' + item2.value"
                          >                          
                          </dd>
                        </dl>
                      </div>
                      </div>
                  </el-dialog>
              </div>
                </el-badge>
                </div>
                <el-button type="primary" @click="getOptionList()" class="selectbtn">预览</el-button>
                <el-button type="primary" @click="onSubmit('PaperForm')" class="btn-padding  btn-margin  selectbtn" :loading="btnFormLoading">立即保存</el-button>
              </div>
              </el-footer>
        </el-aside>
        <el-main>          
          <ViewAdd v-if="ViewAddIF" v-on:listenToViewAdd="listenToViewAdd"></ViewAdd>
          <ViewImport v-if="ViewImportIF"></ViewImport>
          <ViewSelect v-show="ViewSelectIF" v-on:listenToViewSelect="listenToViewSelect"></ViewSelect>   
        </el-main>
      </el-container>

    </el-container>
    
  </div>
</template>
<script>

import ViewAdd from '@/views/quiz/components/add'
import ViewImport from '@/views/quiz/components/import'
import ViewSelect from '@/views/quiz/components/select'
import { fetchAdd } from '@/api/quiz'
import { fetchTree } from '@/api/profession'
import { fetchOptionList } from '@/api/question'
import { Message } from 'element-ui'
import { checkNumber, isvalidateRequired } from '@/utils/validate'
import { numberConvertLetter } from '@/utils/index'

export default {
  components: {
    ViewAdd,
    ViewImport,
    ViewSelect
  },
  data() {
    const validateTitle = (rule, value, callback) => {
      if (!isvalidateRequired(value)) {
        callback(new Error('请输入试卷名称'))
      } else {
        callback()
      }
    }
    const validateTypeList = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error('请选择试卷分类'))
      } else {
        callback()
      }
    }
    const validateExamTime = (rule, value, callback) => {
      if (!isvalidateRequired(value)) {
        callback(new Error('请输入答卷时长'))
      } else {
        if (!checkNumber(value)) {
          callback(new Error('必须是数字'))
        } else {
          callback()
        }
      }
    }
    const validatePassLine = (rule, value, callback) => {
      if (!isvalidateRequired(value)) {
        callback(new Error('请输入通过分数'))
      } else {
        if (!checkNumber(value)) {
          callback(new Error('必须是数字'))
        } else {
          if (value > this.questionScore) {
            callback(new Error('通过分数必须小于题目分数'))
          } else {
            callback()
          }
        }
      }
    }
    const validateRemarks = (rule, value, callback) => {
      if (!isvalidateRequired(value)) {
        callback(new Error('请输入试卷名称'))
      } else {
        callback()
      }
    }
    return {
      ViewAddIF: false,
      ViewImportIF: false,
      ViewSelectIF: true,
      options: [],
      tableData: [],
      dialogVisible: false,
      btnFormLoading: false,
      dialogLoading: false,
      questionCount: 0,
      questionScore: 0,
      formState: 0,
      ids: '',
      PaperForm: {
        title: '',
        examTime: '',
        typeList: [],
        passLine: '',
        remarks: '',
        questionList: []
      },
      goods: [

      ],
      rules: {
        title: [
          { required: true, trigger: 'blur', validator: validateTitle }
        ],
        typeList: [
          { required: true, trigger: 'change', validator: validateTypeList }
        ],
        examTime: [
          { required: true, trigger: 'blur', validator: validateExamTime }
        ],
        passLine: [
          { required: true, trigger: 'blur', validator: validatePassLine }
        ],
        remarks: [
          { required: true, trigger: 'blur', validator: validateRemarks }
        ],
        questionOptionList: []
      }
    }
  },
  created() {
    this.getTree()
    if (isvalidateRequired(this.params.id)) {
      console.log(this.params.id)
    }
  },
  methods: {
    numberConvertLetterFun(number) {
      return numberConvertLetter(number)
    },
    listenToViewAdd: function(data) {
      this.tableData = data
      this.questionCount = this.tableData.length
    },
    listenToViewSelect: function(msg) {
      if (msg.length !== 0) {
        this.tableData = msg
        this.questionCount = this.tableData.length
      }
    },
    deleteRow(index, rows) {
      rows.splice(index, 1)
      this.questionCount--
    },
    sumScore() {
      this.PaperForm.questionList = []
      this.questionScore = 0
      this.formState = 0
      for (var i = 0; i < this.tableData.length; i++) {
        var data = { id: this.tableData[i].id, score: this.goods[i] }
        this.PaperForm.questionList.push(data)
        if (checkNumber(this.goods[i])) {
          this.questionScore += parseInt(this.goods[i])
        } else {
          this.formState++
        }
      }
    },
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.btnFormLoading = true
          this.sumScore()
          if (this.questionCount === 0) {
            Message.warning('请添加题目,从右侧列表选择')
            this.btnFormLoading = false
            return false
          }
          if (this.formState > 0) {
            Message.warning('请为所有题目分配分数,必须是数字')
            this.btnFormLoading = false
            return false
          }
          fetchAdd(this.PaperForm).then(response => {
            if (response.data.status === 200) {
              Message.success('保存试卷成功')
              this.goBack()
            } else {
              Message.error('系统异常,保存试卷失败')
            }
            this.btnFormLoading = false
          }).catch(_ => {
            Message.error('系统异常,保存试卷失败!!')
            this.btnFormLoading = false
          })
        } else {
          return false
        }
      })
    },
    getTree() {
      fetchTree(this.listQuery).then(response => {
        this.options = response.data.data
      })
    },
    getOptionList() {
      this.sumScore()
      this.ids = ''
      if (this.tableData.length > 0) {
        this.dialogVisible = true
        this.dialogLoading = true
        this.tableData.forEach(row => {
          this.ids += row.id + ','
        })
        fetchOptionList(this.ids).then(response => {
          if (response.data.status === 200) {
            this.questionOptionList = response.data.data
          } else {
            Message.error('系统异常,预览失败')
          }
          this.dialogLoading = false
        }).catch(_ => {
          Message.error('系统异常,预览失败!!')
          this.dialogLoading = false
        })
      } else {
        Message.warning('请先添加题目')
      }
    },
    showView(viewName) {
      switch (viewName) {
        case 'ViewAdd' :
          this.ViewAddIF = true
          this.ViewImportIF = false
          this.ViewSelectIF = false
          break
        case 'ViewImport' :
          this.ViewAddIF = false
          this.ViewImportIF = true
          this.ViewSelectIF = false
          break
        case 'ViewSelect' :
          this.ViewAddIF = false
          this.ViewImportIF = false
          this.ViewSelectIF = true
          break
      }
    },
    goBack() {
      this.$router.push({
        path: '/index',
        name: 'quiz-index'
      })
    }
  }
}
</script>
<style scoped>
.paper-container .container{
  position: absolute;
  left: 180px;
  right: 0;
  top: 260px;
  bottom: 0;
}
  .margindis{
    margin-left: 20px;
    margin-right: 10px;
  }
  .clearfix::after {
      content: ".";
      clear: both;
      display: block;
      overflow: hidden;
      height: 0;
        }

  .clearfix {
      zoom: 1;
  }
  .el-header {
    color: #333;
    padding: 0;
    margin: 0 auto;
    margin-top: 10px;
  }
  
  .el-header>>>.el-input__inner{
    border: 1px solid #797979;
  }
  .el-header>>>.el-textarea__inner{
    border: 1px solid #797979;
  }
  .el-aside {
    color: #333;
    border-left: 1px solid #000;
    border-top: 1px solid #000;
    position: relative;
  }

  .write-exam>div:first-child{
    width: 78%;
  }
  .write-exam>div:first-child>>>.el-form-item__content {
    width: 92%;
  }
  .scroll-bar {
    overflow-y: scroll;
    width: 100%;
    height: 500px;
  }
  .borderdel>>>.el-table_1_column_1 {
    text-align: center;
    color: #fff;
  }
  .borderdel>>>.el-table_1_column_2>.cell{
    padding: 0 4px;
  }
  .borderdel>>>.el-table_1_column_1>.cell>div{
    background-color: #999;
    padding: 0;
    height: 30px;
    width: 30px;
    line-height: 30px;
    border-radius: 50%;
  }
  .borderdel>>>.el-table__body-wrapper {
    overflow: auto;
  }
  .borderdel>>>tr:nth-child(odd){
    background-color: #D7D7D7;
  }
  .el-header .time-input{
      width: 40%;
   }
  .borderdel .el-input{
    width: 16%!important;
    font-size: 12px;
  }
  .borderdel>>>.el-input__inner{
    padding: 0 10px;
  }
  .el-icon-delete{
    font-size: 20px;
  }
  .borderdel>>>.el-table_1_column_6  {
    text-align: right;
  }
  .btn-layout{
    display: flex;
    justify-content: space-around;
    margin-bottom: 10px;
  }
  .el-main {
    color: #333;
    text-align: center;
    line-height: 30px;
    border: 1px solid #000;
  }
  .el-footer{
    padding: 0;
    border-top: 1px solid #000;
    border-bottom: 1px solid #000;
    position: absolute;
    bottom: 0;
    width: 100%;
    padding-left: 10px;
  }
  .el-footer>.footer{
    margin-top: 2px!important;
  }
  .selectbtn {
    display: inline-block;
    float: right;
    margin: 10px; 
  }
  body > .el-container {
    margin-bottom: 40px;
  }
  .el-table .cell{
    padding-left: 30px!important;
  }
  .el-table .warning-row {
    background: #d7d7d7;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
  .footer p{
    display: inline-block;
  }
  .btn-margin {
    margin-left: 20px;
  }
  .preview {
    display: inline-block;
  }
  /* 预览框试卷样式 */
  .scroll-bar {
    max-height: 400px;
    overflow-y: auto; 
  }
  .test-type {
    padding-left: 40px;
    padding-right: 40px;
    margin-bottom: 20px;
  }
  .test-type h4{
    text-align: center;
    margin: 0;
    font-weight: 400;
  }
  .qr-code {
    position: absolute;
  }
  .qr-code>div{
    display: inline-block;
  }
  .qr-code>div:last-child{
    width: 40px;
    font-size: 12px;
    line-height: 16px;
  }
  .review-container>>>.el-dialog__body{
    padding: 0 20px;
  }
  .test-document {
    margin-bottom: 14px;
  }
  .test-document span{
    margin-right: 20px;
  }
  .test-document span:first-child{
     margin-right: 60px;
  }
  .documet-note{
    display: flex;
    flex: 1;
  }
  .test-document,.documet-note {
    padding-left: 60px;
    padding-right: 40px;
  }
  .documet-note>div:first-child{
    min-width: 70px; 
  }
  .review-body {
    padding: 0 120px;
  }
  .review-body dd{
    margin: 0;
  }
  .review-body dt{
    position: relative;
  }
  .review-body dt span {
    position: absolute;
    right: 0;
  }
</style>
<style>
  body{
    margin: 0;
    padding: 0;
  }
  .borderdel.el-table--border td,.borderdel.el-table--border th {
    border-right: 0;
  }
  .borderdel .el-table__header-wrapper{
    height: 0;
  }
</style>

